package router

import (
	"gdshop-admin-go-api/app/controllers/activity"
	"gdshop-admin-go-api/app/controllers/shop"
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	"gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
)

func regActivity(s *ghttp.Server, versionName, defaultVersionName string) {
	// 路由前缀
	routerPrefix := "/shop"
	// 优惠券
	s.Group(routerPrefix+"/coupon", func(group *ghttp.RouterGroup) {
		group.Middleware(MiddlewareIsMemberLogin)

		c := shop.NewCouponController(&BaseReq.I{
			TableName:          "coupon",
			InfoIgnoreProperty: "delete_at", // info 时过滤
			PageQueryOp: &BaseReq.QueryOp{
				SelectFields: []string{
					"id",
					"coupon_type",
					"title",
					"quantity_issued",
					"receive_time_type",
					"receive_time_start",
					"receive_time_end",
					"time_type",
					"time_start",
					"time_end",
					"time_days",
					"is_threshold",
					"threshold_money",
					"threshold_num",
					"discount_money",
					"discount_ratio",
					"use_goods_type",
					"receive_limit",
					"can_share",
					"send_new_reg_member",
					"expire_remind",
					"refund_policy",
					"status",
					"create_at",
					"update_at",
					"(SELECT COUNT(1) FROM gd_member_coupon WHERE delete_at < 1 AND coupon_id = a.id) AS received_num",
					"(SELECT COUNT(1) FROM gd_member_coupon WHERE delete_at < 1 AND coupon_id = a.id AND use_time > 0) AS used_num",
				},
				AsName: "a",
				KeyWordLikeFields: []string{
					"title",
				},
				FieldsEq: []string{
					"status",
					"coupon_type",
				},
				OrderBy: "id DESC",
			},
			InfoAfterFn: func(r *ghttp.Request, result map[string]interface{}) (map[string]interface{}, error) {
				useGoodsType := gconv.Int(result["use_goods_type"])

				if useGoodsType > 0 {
					json, err := gjson.LoadContent(result["use_src_ids"])
					if err != nil {
						return nil, err
					}
					result["use_src_ids"] = json.Array()
				} else {
					result["use_src_ids"] = g.Slice{}
				}
				timeStart := gconv.Int64(result["time_start"])
				timeEnd := gconv.Int64(result["time_end"])
				if timeStart > 0 {
					result["time_start"] = gtime.NewFromTimeStamp(timeStart).Format("Y-m-d H:i:s")
				}
				if timeEnd > 0 {
					result["time_end"] = gtime.NewFromTimeStamp(timeEnd).Format("Y-m-d H:i:s")
				}

				receiveTimeStart := gconv.Int64(result["receive_time_start"])
				receiveTimeEnd := gconv.Int64(result["receive_time_end"])
				if receiveTimeStart > 0 {
					result["receive_time_start"] = gtime.NewFromTimeStamp(receiveTimeStart).Format("Y-m-d H:i:s")
				}
				if receiveTimeEnd > 0 {
					result["receive_time_end"] = gtime.NewFromTimeStamp(receiveTimeEnd).Format("Y-m-d H:i:s")
				}

				// 返回 已使用、已领用
				count, err := db.GetUnSafaTableAddDeleteWhere(r.GetCtx(), "member_coupon").Where("coupon_id",
					result["id"]).Fields("1").Count()
				if err != nil {
					count = 0
				}
				result["received_num"] = count
				count, err = db.GetUnSafaTableAddDeleteWhere(r.GetCtx(), "member_coupon").Where(
					"coupon_id = ? AND use_time > 0",
					result["id"]).Fields("1").Count()
				if err != nil {
					count = 0
				}
				result["used_num"] = count

				excludeGoodsIds := gconv.String(result["exclude_goods_ids"])
				if excludeGoodsIds != "" {
					egiJson, err := gjson.LoadContent(excludeGoodsIds)
					if err != nil {
						result["exclude_goods_ids"] = g.Slice{}
					} else {
						result["exclude_goods_ids"] = egiJson.Array()
					}
				}

				return result, nil
			},
			AddBeforeFn: func(r *ghttp.Request, data map[string]interface{}) *response.JsonResponse {
				timeStart := r.GetString("time_start")
				timeEnd := r.GetString("time_end")
				if timeStart != "" {
					data["time_start"] = gtime.NewFromStr(timeStart).Unix()
				} else {
					data["time_start"] = 0
				}
				if timeEnd != "" {
					data["time_end"] = gtime.NewFromStr(timeEnd).Unix()
				} else {
					data["time_end"] = 0
				}
				receiveTimeType := r.GetInt("receive_time_type", 0)
				if receiveTimeType == 0 {
					data["receive_time_start"] = 0
					data["receive_time_end"] = 0
				} else {
					data["receive_time_start"] = gtime.NewFromStr(r.GetString("receive_time_start")).Unix()
					data["receive_time_end"] = gtime.NewFromStr(r.GetString("receive_time_end")).Unix()
				}
				delete(data, "receive_time")
				data["use_src_ids"] = r.GetString("use_src_ids")
				data["exclude_goods_ids"] = r.GetString("exclude_goods_ids")
				return response.SuccessByRequest(r)
			},
			UpdateBeforeFn: func(r *ghttp.Request, data map[string]interface{}) *response.JsonResponse {
				timeStart := r.GetString("time_start")
				timeEnd := r.GetString("time_end")
				if timeStart != "" {
					data["time_start"] = gtime.NewFromStr(timeStart).Unix()
				} else {
					data["time_start"] = 0
				}
				if timeEnd != "" {
					data["time_end"] = gtime.NewFromStr(timeEnd).Unix()
				} else {
					data["time_end"] = 0
				}
				receiveTimeType := r.GetInt("receive_time_type", 0)
				if receiveTimeType == 0 {
					data["receive_time_start"] = 0
					data["receive_time_end"] = 0
				} else {
					data["receive_time_start"] = gtime.NewFromStr(r.GetString("receive_time_start")).Unix()
					data["receive_time_end"] = gtime.NewFromStr(r.GetString("receive_time_end")).Unix()
				}
				delete(data, "receive_time")
				data["use_src_ids"] = r.GetString("use_src_ids")
				data["exclude_goods_ids"] = r.GetString("exclude_goods_ids")
				return response.SuccessByRequest(r)
			},
		})
		controllerMaps := map[string]interface{}{
			"1.0.0": c,
		}
		// 注册基础方法
		regBase([]string{
			"add",
			"delete",
			"update",
			"info",
			"list",
			"page",
		}, group, controllerMaps, versionName, defaultVersionName)

		group.POST("/change_status", func(r *ghttp.Request) {
			BindHandlerVersion(r, versionName, controllerMaps, defaultVersionName, "ChangeStatus")
		})

		group.GET("/get_remark", func(r *ghttp.Request) {
			BindHandlerVersion(r, versionName, controllerMaps, defaultVersionName, "GetRemark")
		})

		group.POST("/set_remark", func(r *ghttp.Request) {
			BindHandlerVersion(r, versionName, controllerMaps, defaultVersionName, "SetRemark")
		})

		group.POST("/ending", func(r *ghttp.Request) {
			BindHandlerVersion(r, versionName, controllerMaps, defaultVersionName, "Ending")
		})
	})
	// 活动
	s.Group(routerPrefix+"/goodsActivity", func(group *ghttp.RouterGroup) {
		group.Middleware(MiddlewareIsMemberLogin)

		c := activity.NewGoodsActivityController(&BaseReq.I{
			TableName:          "goods_activity",
			InfoIgnoreProperty: "delete_at", // info 时过滤
			PageQueryOp: &BaseReq.QueryOp{
				SelectFields: []string{
					"id",
					"activity_name",
					"activity_tag",
					"start_time",
					"end_time",
					"status",
					"activity_type",
					"goods_type",
					"remark",
					"sort",
					"create_at",
					"update_at",
				},
				AsName:  "ga",
				OrderBy: "sort DESC,id ASC",
			},
			InfoAfterFn: func(r *ghttp.Request, result map[string]interface{}) (map[string]interface{}, error) {
				goodsType := gconv.Int(result["goods_type"])
				if goodsType > 0 {
					json, err := gjson.LoadContent(gconv.String(result["goods_ids"]))
					if err != nil {
						return nil, err
					}
					result["goods_ids"] = json.Array()
				} else {
					result["goods_ids"] = g.Slice{}
				}
				excludeGoodsIds := gconv.String(result["exclude_goods_ids"])
				if excludeGoodsIds != "" {
					egiJson, err := gjson.LoadContent(excludeGoodsIds)
					if err != nil {
						result["exclude_goods_ids"] = g.Slice{}
					} else {
						result["exclude_goods_ids"] = egiJson.Array()
					}
				}
				return result, nil
			},
			UpdateBeforeFn: func(r *ghttp.Request, data map[string]interface{}) *response.JsonResponse {
				goodsType := gconv.Int(data["goods_type"])
				if goodsType > 0 {
					data["goods_ids"] = gconv.String(data["goods_ids"])
				} else {
					data["goods_ids"] = "[]"
				}
				data["exclude_goods_ids"] = gconv.String(data["exclude_goods_ids"])

				return response.SuccessByRequestMessage(r, "")
			},
		})
		controllerMaps := map[string]interface{}{
			"1.0.0": c,
		}
		// 注册基础方法
		regBase([]string{
			"add",
			"delete",
			"update",
			"info",
			"list",
			"page",
		}, group, controllerMaps, versionName, defaultVersionName)

		group.POST("/setStatus", func(r *ghttp.Request) {
			BindHandlerVersion(r, versionName, controllerMaps, defaultVersionName, "SetStatus")
		})

		group.GET("/getRule", func(r *ghttp.Request) {
			BindHandlerVersion(r, versionName, controllerMaps, defaultVersionName, "GetRule")
		})

		group.POST("/setRule", func(r *ghttp.Request) {
			BindHandlerVersion(r, versionName, controllerMaps, defaultVersionName, "SetRule")
		})

		group.GET("/getExcludeGoodsSelects", func(r *ghttp.Request) {
			BindHandlerVersion(r, versionName, controllerMaps, defaultVersionName, "GetExcludeGoodsSelects")
		})
	})
}
